package com.ccteam.fluidmusic.ui.search

import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.map
import com.ccteam.fluidmusic.fluidmusic.common.MusicServiceConnectionFlow
import com.ccteam.fluidmusic.utils.cancelIfActive
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment
import com.ccteam.shared.domain.search.HomeSearchMusicDataUseCase
import com.ccteam.shared.result.music.DefaultMusicItem
import com.ccteam.shared.utils.getPlaybackStatus
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/16
 *
 * 首页搜索音乐结果ViewModel
 */
@HiltViewModel
class HomeSearchMusicResultViewModel @Inject constructor(
    private val musicServiceConnectionFlow: MusicServiceConnectionFlow,
    homeSearchMusicDataUseCase: HomeSearchMusicDataUseCase,
    savedStateHandle: SavedStateHandle
): ViewModel() {

    val type: Int = savedStateHandle["type"] ?: AddOnlineMediaFragment.TYPE_SEARCH

    private val _musicList = homeSearchMusicDataUseCase(Pair(savedStateHandle[SEARCH_KEY],type != AddOnlineMediaFragment.TYPE_SEARCH))
        .cachedIn(viewModelScope).asLiveData().let {
            it as MutableLiveData<PagingData<DefaultMusicItem>>
        }

    val musicList: LiveData<PagingData<DefaultMusicItem>> get() = _musicList

    private var metadataChangedJob: Job? = null

    init {

        metadataChangedJob = viewModelScope.launch {
            musicServiceConnectionFlow.nowPlaying.collectLatest {
                refreshNowPlaying()
            }
        }
    }

    fun refreshNowPlaying(){
        val newMusicList = _musicList.value ?: return

        newMusicList.map { item ->
            item.copy(playbackRes = musicServiceConnectionFlow.nowPlaying.value.getPlaybackStatus(item.mediaId))
        }.let {
            _musicList.value = (it)
        }
    }

    override fun onCleared() {
        super.onCleared()

        metadataChangedJob.cancelIfActive()
    }
}